"""每日学习路由"""
from fastapi import APIRouter, HTTPException, Body
from typing import Dict, Any, Optional
from app.services.daily_learning_service import daily_learning_service

router = APIRouter()


@router.get("/daily-learning/{user_id}/{plan_id}")
async def get_daily_questions(
    user_id: str,
    plan_id: str,
    date: Optional[str] = None
):
    """获取每日学习题目"""
    daily_task = await daily_learning_service.get_daily_questions(
        user_id, plan_id, date
    )
    return daily_task


@router.post("/daily-learning/submit")
async def submit_daily_answer(
    user_id: str = Body(...),
    plan_id: str = Body(...),
    question_id: str = Body(...),
    user_answer: str = Body(...),
    user_notes: Optional[str] = Body(None),
    marked_wrong: bool = Body(False)
):
    """提交每日学习答案（支持标记错误和备注）"""
    result = await daily_learning_service.submit_daily_answer(
        user_id, plan_id, question_id, user_answer, user_notes, marked_wrong
    )
    return result


@router.get("/daily-learning/wrong-questions/{user_id}")
async def get_wrong_questions(user_id: str):
    """获取错题本"""
    wrong_questions = await daily_learning_service.get_wrong_questions(user_id)
    return {
        "user_id": user_id,
        "total": len(wrong_questions),
        "questions": wrong_questions
    }


@router.post("/daily-learning/activate-plan/{plan_id}")
async def activate_plan(
    plan_id: str,
    data: Dict[str, Any] = Body(...)
):
    """激活学习计划（开始学习）"""
    user_id = data.get("user_id", "user_001")
    # 保存激活的计划
    saved_to_redis = False
    try:
        from app.core.database import RedisClient
        redis = RedisClient.get_client()
        redis.ping()
        redis.set(f"active_plan:{user_id}", plan_id)
        redis.expire(f"active_plan:{user_id}", 86400 * 365)  # 保存1年
        saved_to_redis = True
        print(f"✅ [激活计划] 计划已保存到Redis: active_plan:{user_id} = {plan_id}")
    except Exception as e:
        print(f"⚠️ Redis连接失败: {e}，将使用文件存储")
    
    # 如果Redis不可用，使用文件存储
    if not saved_to_redis:
        try:
            from app.services.file_storage_service import file_storage_service
            file_storage_service.set(f"active_plan:{user_id}", plan_id, expire=86400 * 365)
            print(f"✅ [文件存储] 激活计划已保存到文件: active_plan:{user_id} = {plan_id}")
        except Exception as e2:
            print(f"⚠️ 文件存储失败: {e2}")
            # 最后的后备：内存存储
            try:
                from app.services.user_onboarding_service import user_onboarding_service
                if not hasattr(user_onboarding_service, '_memory_storage'):
                    user_onboarding_service._memory_storage = {}
                user_onboarding_service._memory_storage[f"active_plan:{user_id}"] = plan_id
                print(f"✅ [内存存储] 激活计划已保存到内存: active_plan:{user_id} = {plan_id}")
            except Exception as e3:
                print(f"⚠️ 内存存储也失败: {e3}")
    
    # 生成今日学习任务
    daily_task = await daily_learning_service.get_daily_questions(user_id, plan_id)
    
    return {
        "plan_id": plan_id,
        "user_id": user_id,
        "status": "activated",
        "daily_task": daily_task,
        "message": "学习计划已激活，开始今日学习吧！"
    }


@router.get("/daily-learning/statistics/{user_id}/{plan_id}")
async def get_today_statistics(
    user_id: str,
    plan_id: str,
    date: Optional[str] = None
):
    """获取今日学习统计"""
    statistics = await daily_learning_service.get_today_statistics(user_id, plan_id, date)
    return statistics


@router.post("/daily-learning/continue/{user_id}/{plan_id}")
async def continue_learning(
    user_id: str,
    plan_id: str
):
    """继续学习（获取新的训练题目）"""
    # 获取新的每日题目（会生成新的题目列表）
    from datetime import datetime
    import time
    today = datetime.now().strftime("%Y-%m-%d")
    
    # 清除今日题目缓存，强制生成新题目
    daily_questions_key = f"daily_questions:{user_id}:{today}"
    
    # 清除Redis缓存
    try:
        from app.core.database import RedisClient
        redis = RedisClient.get_client()
        redis.ping()
        redis.delete(daily_questions_key)
        print(f"✅ [继续学习] 已清除Redis缓存: {daily_questions_key}")
    except Exception as e:
        print(f"⚠️ [继续学习] Redis清除失败: {e}")
    
    # 清除内存缓存
    if hasattr(daily_learning_service, '_daily_questions_cache'):
        if daily_questions_key in daily_learning_service._daily_questions_cache:
            del daily_learning_service._daily_questions_cache[daily_questions_key]
            print(f"✅ [继续学习] 已清除内存缓存: {daily_questions_key}")
    
    # 清除文件存储缓存
    try:
        from app.services.file_storage_service import file_storage_service
        file_storage_service.delete(daily_questions_key)
        print(f"✅ [继续学习] 已清除文件缓存: {daily_questions_key}")
    except Exception as e:
        print(f"⚠️ [继续学习] 文件缓存清除失败: {e}")
    
    # 生成新的每日学习任务（会生成新题目，80%新题+20%复习）
    # 注意：这里会重新调用get_daily_questions，由于缓存已清除，会生成新题目
    daily_task = await daily_learning_service.get_daily_questions(user_id, plan_id)
    
    return {
        "user_id": user_id,
        "plan_id": plan_id,
        "daily_task": daily_task,
        "message": "已为您生成新的训练题目（80%新题，20%复习，错题优先），继续加油！"
    }

